/**
 * Created by rongyao on 2017/10/17.
 */
var mongoose = require('mongoose');
const User = require('../models/users.model');

exports.create = function (req, res, next) {
	var user = new User(req.body);
	user.save().then(data => {
		res.json(data);
	});
}

exports.get = function (req, res, next) {
	var id = req.params.id;
	User.findById(id, function (err, data) {
		res.json(data);
	})
}

exports.update = function (req, res, next) {
	var id = req.params.id;
	User.findByIdAndUpdate(id, {$set: req.body}, {new: false})
		.then(data => {
			res.json(data);
		})
}

exports.remove = function (req, res, next) {
	var id = req.params.id;
	User.findByIdAndRemove(id, function (data) {
		res.json(data);
	})
}

exports.list = function (req, res, next) {
	var page = req.body.page ? req.body.page : 1;
	var limit = req.body.rows ? req.body.rows : 10;
	var queryCondition = {};
	if (req.body.username && req.body.username.trim().length > 0) {
		username = req.body.username;
		queryCondition = {
			"username": new RegExp(username, 'i'),
		}
	}
	User.paginate(queryCondition, {page: page - 0, limit: limit - 0, sort: {date: -1}}, function (err, result) {
		result.rows = result.docs;
		delete result.docs;
		res.json(result);
	});
}

exports.deletes = function (req, res, next) {
	var ids = req.body.ids;
	console.log(ids);
	if(ids.split(',').length>0){
		User.remove({_id: {$in: ids.split(',')}}).then(data=>{
			res.json({'msg':"删除成功"})
		})
	}
}